<template>
  <div class="form-layout">
    <customSpace fullWidth style="padding: 5px 10px" v-if="!propReadonly">
      <template #content>
          <customButton  title="保存" theme="primary" v-if="0 == form.closeFlag" @click="certOp('save','保存', true)"/>
          <customButton  title="提交升级" v-if="!cpFormNew &&  0 == form.closeFlag" theme="success" @click="certOp('upgrade','提交升级', true)"/>
          <customButton  title="删除" v-if="!cpFormNew && 0 == form.closeFlag"  theme="danger"  @click="certOp('delete','删除')"/>
          <customButton  title="作废"  v-if="!cpFormNew  &&  0 == form.closeFlag" theme="warning"  @click="certOp('closeCert','作废')"/>

<!--        <customButton  title="查看历史"  v-if="!cpFormNew" theme="default"  @click="certOp('viewHis')"/>-->
      </template>
    </customSpace>

    <customForm :data="form" :rules="cpPropRules" ref="editForm" :disabled="propReadonly">
      <template #content>
        <div id="box-data" class="box-title">{{cpBusinessTypeTttle + '信息'}}</div>
        <!-- 供应商信息-->
        <template v-if="constCommon.certTypeNameMap.sp.businessTypeCode == form.businessTypeCode">
          <customFormItem label="名称" name="name" :parent="_self" :form="certInfo" disabled/>
          <customFormItem label="信用代码" name="companyCode" :parent="_self" :form="certInfo"  disabled/>
        </template>

        <!-- 厂商信息-->
        <template v-if="constCommon.certTypeNameMap.mfg.businessTypeCode == form.businessTypeCode">
          <customFormItem label="名称" name="name" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="信用代码" name="companyCode" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="生产许可证" name="productionLicence" :parent="_self" :form="certInfo"  disabled/>
        </template>

        <!-- 品类信息-->
        <template v-if="constCommon.certTypeNameMap.cat.businessTypeCode == form.businessTypeCode">
          <customFormItem label="名称" name="name" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="代码" name="code" :parent="_self" :form="certInfo"  disabled/>
        </template>

        <!-- 商品信息-->
        <template v-if="constCommon.certTypeNameMap.matr.businessTypeCode == form.businessTypeCode">
          <customFormItem label="品名" name="materialName" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="商品名" name="materialTradeName" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="注册证" name="certificateNo" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="注册证开始" name="certificateExpiredStartDate" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="注册证截止" name="certificateExpiredDate" :parent="_self" :form="certInfo"  disabled/>
          <customFormItem label="批准文号" name="approvalNo" :parent="_self" :form="certInfo"  disabled/>
        </template>


        <div id="box-base" class="box-title">资质信息</div>

        <customFormItem
          label="资质类型"
          name="certificateId"
          :parent="_self"
          :form="form"
          :type="constCommon.formItemType.selectStatic.name"
          :config="{options: utils.getCertTypeList(form.businessTypeCode)}"
          :disabled="!cpFormNew"
          help="保存后不可修改"
          full-width
          @change="certificateIdChange"
        />

        <customFormItem label="签发方" name="certificateSign" :parent="_self" :form="form" full-width/>
        <customFormItem label="授予方" name="certificateSignTo" :parent="_self" :form="form"  full-width/>
        <customFormItem label="资质编号" name="certificateNo" :parent="_self" :form="form" v-show="1 == form.needCertificateNo"  full-width :scanBtn="true"/>
        <customFormItem label="效期开始" name="expiryStartDate" :parent="_self" :form="form"
                        :type="constCommon.formItemType.datePicker.name"
                        v-show="1 == form.needExpiryDate"
                        full-width
        />
        <customFormItem label="效期结束" name="expiryDate" :parent="_self" :form="form"
                        :type="constCommon.formItemType.datePicker.name"
                        v-show="1 == form.needExpiryDate"
                        full-width
        />
        <customFormItem label="版本" name="version" :parent="_self" :form="form" disabled  full-width/>
        <customFormItem
          label="状态"
          name="statusType"
          :parent="_self"
          :form="form"
          :type="constCommon.formItemType.slot.name"
          v-show="!cpFormNew"
        >
          <template #content>
            <span style="font-size: 12px">
               已提交
              <span style="margin-right: 10px" v-html="utils.getDictLabel(form.submitFlag,constCommon.dictType.commonYesNo, '',true)">
              </span>

              已作废
              <span v-html="utils.getDictLabel(form.closeFlag,constCommon.dictType.commonYesNo, '',true)">
              </span>
            </span>

          </template>
        </customFormItem>
        <customFormItem label="备注" name="remark" :parent="_self" :form="form"
                        :type="constCommon.formItemType.textarea.name"
                        fullWidth
                        :config="{maxlength: 200, minRows: 1, maxRows: 5}"
        />


        <div id="box-img" class="box-title">资质附件</div>
        <customFormItem
          label=""
          name="certFile"
          :parent="_self"
          :form="form"
          :type="constCommon.formItemType.slot.name"
          fullWidth
          style="height: 200px; padding-left: 10px;"
        >
          <template #content>
            <customUpload
              :data="{ fileRefId: form.id, fileRefTable: 'certificate_repository', fileSavePath: 'certificate_repository',fileInfoIdArr: form.docIds,fileInfoField: 'doc_ids'}"
              :hide="cpFormNew"
              hideMsg="请先保存后再上传"
              :disabled="propReadonly"
            />
          </template>
        </customFormItem>
      </template>
    </customForm>

    <!--资质类型选择-->
    <tableDrawer :queryWrapper="cpTableDrawerTypeQueryWrapper" ref="tableDrawerType" refName="tableDrawerType" @confirm="tableDrawerTypeConfirm" viewKey="certificates_select" attach="body"/>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
import customUpload from '@/components/custom/form/customUpload.vue'

export default {
  help: '资质-详情',
  data() {
    return {
      form: {},
      certInfo: {},
      viewData: {},
      certTypeList: [],
    }
  },
  methods: {
    // 资质类型选择后
    tableDrawerTypeConfirm(row, refName) {
      this.$set(this.form, 'certificateId', row.id)
      this.$set(this.form, 'certificateName', row.name)
      this.$set(this.form, 'needExpiryDate', row.needExpiryDate)
      this.$set(this.form, 'needCertificateNo', row.needCertificateNo)
    },
    // 新增初始化
    initNew() {
      if (!this.cpFormNew) {
        return
      }
      this.$set(this.form, 'version', 1)
      this.$set(this.form, 'closeFlag', 0)
      this.$set(this.form, 'submitFlag', 0)
      this.$set(this.form, 'targetDescribeId', this.propInitData.targetDescribeId)
      this.$set(this.form, 'supplierId', this.propInitData.spId)
      this.$set(this.form, 'supplierName', this.propInitData.spName)
      this.$set(this.form, 'businessTypeCode', this.constCommon.certTypeNameMap[this.propInitData.typeName].businessTypeCode)
      let certExtName = this.propInitData.spName
      switch (this.propInitData.typeName) {
        // 供应商资质
        case this.constCommon.certTypeNameMap.sp.key: {
          break
        }
        // 厂商资质
        case this.constCommon.certTypeNameMap.mfg.key: {
          this.$set(this.form, 'manufacturerId', this.propInitData.mfgId)
          this.$set(this.form, 'manufacturerName', this.propInitData.mfgName)
          certExtName = this.propInitData.mfgName
          break
        }
        // 分类资质
        case this.constCommon.certTypeNameMap.cat.key: {
          this.$set(this.form, 'manufacturerId', this.propInitData.mfgId)
          this.$set(this.form, 'manufacturerName', this.propInitData.mfgName)
          this.$set(this.form, 'catalogId', this.propInitData.catId)
          this.$set(this.form, 'catalogName', this.propInitData.catName)
          certExtName = this.propInitData.catName
          break
        }
        // 商品资质
        case this.constCommon.certTypeNameMap.matr.key: {
          this.$set(this.form, 'manufacturerId', this.propInitData.mfgId)
          this.$set(this.form, 'manufacturerName', this.propInitData.mfgName)
          this.$set(this.form, 'catalogId', this.propInitData.catId)
          this.$set(this.form, 'catalogName', this.propInitData.catName)
          this.$set(this.form, 'materialName', this.propInitData.matrName)
          this.$set(this.form, 'materialId', this.propInitData.matrId)
          certExtName = this.propInitData.matrName
          break
        }
      }
      this.$set(this.form, 'certExtName', certExtName)
      console.log('this.form', this.form)
    },

    // 资质信息
    getCertInfo() {
      this.certInfo = {}
      let config = Object.values(this.constCommon.certTypeNameMap).find(tmp => tmp.businessTypeCode == this.form.businessTypeCode)
      if (config) {
        let getAddr = `${config.findById}?id=${this.form[config.id]}`
        this.$ajax.get(getAddr).then((response) => {
          if (response.code == 0) {
            this.certInfo = response.data
          }
        })
      }
    },

    // 初始化表单
    initForm(form = {}) {
      this.form = global.utils.jsonClone(form)
      this.$set(this.form, 'id', this.form.id)
      this.initNew()
      this.getCertInfo()
    },

    // 关闭窗口
    closeForm() {
      this.$emit('close')
    },

    //资质类型选择
    certificateIdChange(value,row) {
      this.$set(this.form, 'certificateId', row.id)
      this.$set(this.form, 'certificateName', row.name)
      this.$set(this.form, 'needExpiryDate', row.needExpiryDate)
      this.$set(this.form, 'needCertificateNo', row.needCertificateNo)
    },

    // 操作
    certOp(type, msg, validForm = false) {
      if (validForm) {
        this.$refs.editForm.validate().then((result) => {
          if (result && result == true) {
            this.utilMessage.confirm(`确认${msg}么`, () => {
              this._certOp(type)
            })
          }
        })
        return
      }
      if (msg) {
        this.utilMessage.confirm(`确认${msg}么`, () => {
          this._certOp(type)
        })
        return
      }
      this._certOp(type)
    },

    // 操作
    _certOp(type) {
      console.log('type', type)
      this.form.opType = type
      switch (type) {
        //保存 或者 提交升级
        case 'save':
        case 'upgrade': {
          this.utilVue.loadShow(true)
          this.$ajax
          .post('/cert/certificate_repositorys/saveOrUpdateCommon', this.form)
          .then((resp) => {
            this.utilVue.loadHide()
            if (resp.code == 0) {
              this.utilMessage.success(resp.msg)
              this.initForm(resp.data)
            }
          })
          break
        }
        //删除
        case 'delete': {
          this.utilVue.loadShow(true)
          this.$ajax
            .delete('/cert/certificate_repositorys/deleteBatchCommon', {data: {ids: [this.form.id]}})
            .then((resp) => {
              this.utilVue.loadHide()
              if (resp.code == 0) {
                this.utilMessage.success(resp.msg)
                this.closeForm()
              }
            })
          break
        }
        //作废
        case 'closeCert': {
          this.utilVue.loadShow(true)
          this.$ajax
            .post(`/cert/certificate_repositorys/close/${this.form.id}`, {})
            .then((resp) => {
              this.utilVue.loadHide()
              if (resp.code == 0) {
                this.utilMessage.success(resp.msg)
                this.closeForm()
              }
            })
          break
        }
        //查看历史
        case 'viewHis': {
          break
        }
      }
    }
  },
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        if (1 != this.form.needCertificateNo) {
          this.$set(this.form, 'certificateNo', null)
        }
        if (1 != this.form.needExpiryDate) {
          this.$set(this.form, 'expiryStartDate', null)
          this.$set(this.form, 'expiryDate', null)
        }
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData) => {

      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      },
      afterClick(button, data) {
        let {key: buttonKey} = button
        // 提交升级
        if (buttonKey == 'upgrade') {
          that.utilMessage.confirm('是否提交升级', () => {
            that.$set(that.form, 'opType', 'upgrade')
            that.propParent.ocAsynSaveViewForm()
          })
        }
      },
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
  },
  components: { customAnchor, customUpload },
  computed: {
    // 资质类型选择查询条件
    cpTableDrawerTypeQueryWrapper() {
      let wrapper = this.$newWrapper()
      wrapper.eq('business_type_code', this.strings.defaultIfBlank(this.form.businessTypeCode, '-1'))
      return wrapper
    },
    // 资质类型名称
    cpBusinessTypeTttle() {
      let title = ''
      Object.keys(this.constCommon.certTypeNameMap).forEach(key => {
        if (this.constCommon.certTypeNameMap[key].businessTypeCode == this.form.businessTypeCode) {
          title = this.constCommon.certTypeNameMap[key].title
        }
      })
      return title
    },
    // 是否是新增
    cpFormNew() {
      return this.strings.isBlank(this.form.id)
    },

    // 校验规则
    cpPropRules() {
      let rule = this.propRules || {}
      rule.certificateId = [{ required: true, message: '请选择', trigger: 'blur' }]
      return rule
    }
  },
}
</script>
